package com.celeritymq.destination;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.net.SocketAddress;
import javax.jms.Destination;

import com.celeritymq.handler.Handler;

public class DestinationContainer {
	private static ConcurrentMap<Destination, Set<Dealer>> map = new ConcurrentHashMap<Destination, Set<Dealer>>();
	public static synchronized boolean register(Destination destination, SocketAddress socketAddress, Handler handler) {
		Dealer dealer=new Dealer(socketAddress, handler);
		Set<Dealer> addressSet = map.get(destination);
		if (addressSet == null) {
			addressSet = new HashSet<Dealer>();
			map.put(destination, addressSet);
		}
		return addressSet.add(dealer);
	}

	public static Set<Dealer> getAddressByDestination(Destination destination) {
		return map.get(destination);
	}
	
	public static class Dealer{
		private SocketAddress address;
		private Handler handler;
		public Dealer(SocketAddress address, Handler handler) {
			super();
			this.address = address;
			this.handler = handler;
		}
		public SocketAddress getAddress() {
			return address;
		}
		public Handler getHandler() {
			return handler;
		}
		@Override
		public int hashCode() {
			final int prime = 31;
			int result = 1;
			result = prime * result + ((address == null) ? 0 : System.identityHashCode(address));
			return result;
		}
		@Override
		public boolean equals(Object obj) {
			if (this == obj)
				return true;
			if (obj == null)
				return false;
			if (getClass() != obj.getClass())
				return false;
			Dealer other = (Dealer) obj;
			if (address == null) {
				if (other.address != null)
					return false;
			} else if (!address.equals(other.address))
				return false;
			return true;
		}
		
	}

}
